﻿using System;
using System.Text;

namespace roysland.net.xcom.core.Helpers
{
    public static class ByteHelper
    {
        public static byte[] GetByteSegment(int offset, int numBytes, byte[] buffer)
        {
            var result = new byte[numBytes];
            var counter = 0;
            for (int i = offset; i < (offset + numBytes); i++)
            {
                if ((offset + numBytes) > buffer.Length)
                    continue;

                result[counter] = buffer[i];
                counter++;
            }

            return result;
        }

        public static string ByteToString(byte[] buffer)
        {
            var enc = new ASCIIEncoding();
            var s = enc.GetString(buffer);
            //_objectName = _objectName.Replace('\0', ' ');
            //_objectName = _objectName.Replace('\n', ' ');
            //_objectName = _objectName.Replace('\r', ' ');

            return s;
        }

        public static byte IntToByte(int value)
        {
            decimal val = value;
            return (byte)val;
        }

        public static byte[] IntToBytes(int value)
        {
            return BitConverter.GetBytes((short)value);
        }

        public static int ByteToInt(int byteNumber, byte[] buffer)
        {
            byte[] buff = GetByteSegment(byteNumber, 1, buffer);
            string val = BitConverter.ToString(buff, 0);
            return Int32.Parse(val, System.Globalization.NumberStyles.HexNumber);
        }

        public static int ByteUGEToInt(int byteNumber, byte[] buffer)
        {
            byte[] buff = GetByteSegment(byteNumber, 1, buffer);
            string val = BitConverter.ToString(buff, 0);
            return Int32.Parse(val);
        }

        public static int BytesToInt(int byteNumber, int numBytes, byte[] buffer)
        {
            byte[] buff = GetByteSegment(byteNumber, numBytes, buffer);
            int val = BitConverter.ToInt16(buff, 0);
            return val;
        }

        
    }
}
